//
//  AttentionTableview.m
//  SoundPill
//
//  Created by 宋旭东 on 15/7/3.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "AttentionTableview.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "NewsetModel.h"
#import "NewestTableViewCell.h"
#define kDeviceHeight [UIScreen mainScreen].bounds.size.height
#define kDeviceWidth  [UIScreen mainScreen].bounds.size.width
@interface AttentionTableview ()<UITableViewDelegate, UITableViewDataSource,MJRefreshBaseViewDelegate>
{
    int page;
    int lastPage;
    int pages;
    NSString *_filePath;
    MJRefreshHeaderView *header;
    MJRefreshFooterView *fotter;
}
@property (strong, nonatomic) UITableView *tableview;
@property (strong, nonatomic) NSMutableArray *attenArray;
@end

@implementation AttentionTableview
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.attenArray = [[NSMutableArray alloc] init];
        [self createTableview];
        NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
        _filePath = [cachPath stringByAppendingPathComponent:@"attention"];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_filePath]) {
            NSData *data = [NSData dataWithContentsOfFile:_filePath];
            NSDictionary *content = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            [self reloadAttentionDataWithResponesObject:content pag:1];
            page = 1;
        } else {
            [header beginRefreshing];
        }

    }
    return self;
}
- (void)createTableview
{
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.showsVerticalScrollIndicator = NO;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableview.separatorColor = [UIColor colorWithRed:0.895 green:0.898 blue:0.908 alpha:1.000];
    [self addSubview:_tableview];
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)])
    {
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)])
    {
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
    }
    //刷新控件
    header = [MJRefreshHeaderView header];
    header.scrollView = _tableview;
    header.delegate = self;
    fotter = [MJRefreshFooterView footer];
    fotter.scrollView = _tableview;
    fotter.delegate = self;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _attenArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_attenArray.count > 0) {
        if ([_attenArray[indexPath.row] isKindOfClass:[NewsetModel class]]) {
            NewsetModel *model = _attenArray[indexPath.row];
            if (model.tags.count > 0) {
                if ([UIScreen mainScreen].bounds.size.height > 667) {
                    return 0.42 * [UIScreen mainScreen].bounds.size.height;
                } else {
                    return 0.4136 * [UIScreen mainScreen].bounds.size.height;
                }
            } else {
                if ([UIScreen mainScreen].bounds.size.width == 320) {
                    return 0.41 * [UIScreen mainScreen].bounds.size.height;
                } else if ([UIScreen mainScreen].bounds.size.height == 667) {
                    return 0.41 * [UIScreen mainScreen].bounds.size.height;
                } else {
                    return 0.42 * [UIScreen mainScreen].bounds.size.height;
                }
            }
        } else {
            return 230;
        }
    } else {
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier1 = @"cell1";
    NewestTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier1];
    if (cell == nil) {
        cell = [[NewestTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier1];
    }
    [cell.tagView removeFromSuperview];
    if (_attenArray.count > 0) {
        cell.model = _attenArray[indexPath.row];
    }
    cell.tagView = [[groundTagsView alloc]initWithFrame:CGRectZero];
    [cell.tagView createTagView:cell.model.tags];
    [cell.contentView addSubview:cell.tagView];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsetModel *mod = _attenArray[indexPath.row];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:mod.id];
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    BOOL isHeader = [refreshView isKindOfClass:[MJRefreshHeaderView class]];
    if (isHeader) {
        page = 1; // 第一页
        fotter.hidden = NO;
        [_attenArray removeAllObjects];
        [self AFNetworking:page refreshing:refreshView];
    }else { // 上拉加载更多
        if (pages == 1 || page == pages) {
            fotter.hidden = YES;
        } else {
            page++;
            [self AFNetworking:page refreshing:refreshView];
        }
    }
}
- (void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{
    
}
- (void)AFNetworking:(int)pag refreshing:(MJRefreshBaseView *)refreshView
{
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/user/works?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadAttentionDataWithResponesObject:responseObject pag:pag];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [refreshView endRefreshing];
        });
        if (pag == 1) {
            //            BOOL result =
//            [operation.responseData writeToFile:_filePath atomically:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [refreshView endRefreshing];
    }];
}
- (void)reloadAttentionDataWithResponesObject:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSDictionary *dic = [bigDic valueForKey:@"data"];
    for (NSDictionary *dict in dic) {
        NewsetModel *model = [[NewsetModel alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        NewsetModel *oldModel = [_attenArray lastObject] ;
        if (![model.id isEqualToString:oldModel.id]) {
            [_attenArray addObject:model];
        }
    }
    NSDictionary *meta = [bigDic valueForKey:@"meta"];
    if (meta != nil) {
        pages = [[meta valueForKey:@"pages"] intValue];
        if (pages == 1 || pag == pages) {
            fotter.hidden = YES;
        }
    }
    _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [_tableview reloadData];
}
#pragma mark -
- (CGFloat)heightForText:(NSString *)text
{
    CGSize size = CGSizeMake(kDeviceWidth - 59, 2000);
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:[UIFont systemFontOfSize:12.0f] forKey:NSFontAttributeName];
    CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    return frame.size.height;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
